<script setup lang="ts">
import { onLoad } from '@dcloudio/uni-app'
import { onMounted, ref } from 'vue'
import dayjs from 'dayjs'
import { navigateTo } from '@uni-helper/uni-promises'
import user from '@/composables/user'
import { SalaryStatusEnum } from '@/constant/enum'
import { getAdvanceDetail, getAdvanceWechat, getSalaryAli } from '@/package-mine/api/pay'
import type { AdvanceInfoDto } from '@/package-mine/api/pay/type'
import { getUnsignedContactList } from '@/api/contract'

interface AdvanceDto extends AdvanceInfoDto {
    endstatus?: number
}
const showNoRegisterPopup = ref(false)
const statusBarHeight = ref(0)
const eventChannel = ref()

const extraData = ref()
const id = ref(0)
const isEdition = ref(false)
const detail = ref<AdvanceDto>({} as AdvanceDto)
const showBottom = ref(false)
const statusMap = ref({
    0: '审核中',
    1: '未通过',
    2: '待领取',
    3: '已领取',
    4: '停止发薪',
    5: '领取失败',
    6: '进行中',
})

enum StatusEnum {
    waitCheck = 0,
    pass = 1,
    fail = 2,
}

async function getData(id: number) {
    const res = await getAdvanceDetail(id)
    // endstatus 最终页面显示的状态 0:'审核中'，1:'未通过'，2:'待领取'，3: '已领取'，4: '停止发薪', 5: '领取失败', 6: '进行中'
    // const finalStatus = {
    //     [StatusEnum.waitCheck]: 0,
    //     [StatusEnum.fail]: 1,
    //     [StatusEnum.pass]: {
    //         [StatusEnum.waitCheck]: 0,
    //         [StatusEnum.fail]: 1,
    //         [StatusEnum.pass]: SalaryStatusEnum,
    //     },
    // }
    // console.log(545454, finalStatus)
    // detail.value.endstatus = finalStatus?.[res.applyStatus as typeof StatusEnum[ keyof typeof StatusEnum]]
    /**
     * applyStatus 一审审批状态  0:待审核，1:已通过，2:未通过
     *
     * auditStatus 二审审批状态  0:待审核，1:通过，2:驳回
     *
     * status 领薪状态 0:待领,1:已领, 2:停止, 3:进行中, 4:领薪失败
     *
     * endstatus 最终页面显示的状态 0:'审核中'，1:'未通过'，2:'待领取'，3: '已领取'，4: '停止发薪', 5: '领取失败', 6: '进行中'
     */

    if (res.applyStatus === 0)
        res.endstatus = 0
    if (res.applyStatus === 2)
        res.endstatus = 1
    if (res.applyStatus === 1) {
        if (res.auditStatus === 0)
            res.endstatus = 0
        if (res.auditStatus === 1) {
            if (res.status === 0)
                res.endstatus = 2
            else if (res.status === 1)
                res.endstatus = 3
            else if (res.status === 2)
                res.endstatus = 4
            else if (res.status === 4)
                res.endstatus = 5
            else if (res.status === 3)
                res.endstatus = 6
        }
        if (res.auditStatus === 2)
            res.endstatus = 1
    }
    detail.value = res
    detail.value = res
}

function onCall() {
    if (detail.value?.phone) {
        uni.makePhoneCall({
            phoneNumber: detail.value?.phone,
        })
    }
    else {
        toast('暂无驻场手机号')
    }
}

/**
 * 跳转到银行卡页面
 *
 * @param otherData 其他数据对象，默认为空对象
 * @returns 无返回值
 */
async function toBank(otherData: AnyObject = {}) {
    const event = await navigateTo({
        url: '/package-mine/pages/bank-card/bank-card',
    })
    event.eventChannel.emit('extraData', {
        extraData: {
            ...extraData.value,
            ...otherData,
            from: 'salary',
        },
    })
}

/**
 * 判断是否无待签署合同
 *
 * @returns 返回 Promise，无待签署合同则 resolve(true)，有待签署合同则 reject(new Error('有合同未签署'))
 */
async function hasNoContact() {
    return new Promise(async (resolve, reject) => {
        const contactList = await getUnsignedContactList({
            companyId: detail.value.companyId,
        })
        if (contactList.length) {
            uni.showModal({
                title: '温馨提示',
                content: `应劳务公司要求，需要您签署合同后领薪，您有${contactList.length}份合同待签署。请前往微信小程序签署。`,
            })
            reject(new Error('有合同未签署'))
        }
        else {
            resolve(true)
        }
    })
}

/**
 * 支付宝领取薪资
 *
 * @returns 无返回值，执行完会跳转到薪资状态页面
 */
async function onGetSalary() {
    shake(async () => {
        await getData(detail.value.recordId)
        if (detail.value.isShowPop) {
            toast('应劳务公司要求，需要您填写完银行卡号码。')
            toBank()
            return
        }
        if (extraData.value?.isCollectOpenBankName === 1 && !user.userInfo.value.openBankName) {
            toast('应劳务公司要求，需要您填写完开户行城市信息。')
            toBank()
            return
        }
        if (detail.value?.isNeedIdCardPhoto === 1 && !user.userInfo.value?.ownIdCardFront && !user.userInfo.value?.ownIdCardBack) {
            toast('未上传身份证照片，请在上传后在进行领取。')
            uni.navigateTo({
                url: '/package-mine/pages/card-info/card-info',
            })
            return
        }

        let data = {
            type: '',
            status: 0,
            message: '',
        }
        const res = getSalaryAli({
            id: detail.value.id,
            phone: user.userInfo.value?.phone,
            detailOrderNo: detail.value?.detailOrderNo,
        }).catch((err) => {
            data = {
                type: 'error',
                status: 3,
                message: err.msg,
            }
        })
        if (!data.type) {
            data = {
                type: 'success',
                status: 1,
                message: '',
            }
        }
        await wait(100)
        const event = await navigateTo({
            url: '/package-mine/pages/salary-status/salary-status',
            events: {
                refresh: () => {
                    getData(id.value)
                },
            },
        })
        event.eventChannel.emit('responseData', {
            ...data,
            id: detail.value.id,
            phone: user.userInfo.value?.phone,
            detailOrderNo: detail.value?.detailOrderNo,
            platform: 'alipay',
        })
    })
}
onLoad(async (options) => {
    statusBarHeight.value = uni.getWindowInfo().statusBarHeight
    // #ifdef MP-ALIPAY
    my.setNavigationBar({
        frontColor: '#ffffff',
        backgroundColor: '#ffffff',
    })
    await user.waitLogin()
    // #endif
    if (options?.id)
        getData(options.id)
    showBottom.value = options?.showBottom !== '0'
})

/**
 * 判断是否注册了微信/是否开通了微工卡
 *
 * @returns 返回一个Promise对象，无返回值
 */
async function isRegistryWechat() {
    return new Promise((resolve, reject) => {
        // 通过有没有openId来判断是否注册了微信
        if (!user.userInfo.value?.openId) {
            showNoRegisterPopup.value = true
            reject(false)
        }
        resolve(true)
    })
}

/**
 * 跳转到领薪结果页
 *
 * @param data 待转化的数据
 * @returns 无返回值
 */
async function toResult(data: AnyObject) {
    const event = await navigateTo({
        url: '/package-mine/pages/salary-status/salary-status',
        events: {
            refresh: () => {
                getData(id.value)
            },
        },
    })
    event.eventChannel.emit('responseData', data)
    // event?.eventChannel.emit('phone', detail.value?.params?.linkmanList || [])
}

/**
 * 提现
 * @param type 领薪的类型 'BANK_ACCOUNT' 领取到微工卡 'WECHATPAY_ACCOUNT' 领取到微信零钱
 * @returns 无返回值
 */
async function getPaid(type: string) {
    shake(async () => {
        if (detail.value?.isNeedIdCardPhoto === 1 && !user.userInfo.value.ownIdCardFront && !user.userInfo.value.ownIdCardBack) {
            const res = await uni.showModal({
                title: '提示',
                content: '未上传身份证照片，请在上传后在进行领取',
            })
            if (res.confirm) {
                uni.navigateTo({
                    url: '/package-mine/pages/card-info/card-info',
                })
                return
            }
            if (res.cancel)
                return
        }

        const data = {
            title: '',
            type: '',
            content: '',
            color: '#FF7E68',
            id: detail.value.companyId,
            // phone: detail.value.params.linkmanList[0].phone,
            order: detail.value?.detailOrderNo,
            payid: detail.value.recordId,
            platform: 'wechat',
            status: 1, // 1 处理中 2 成功 3 失败
            from: 'advance',
            transferScene: type || '',
        }

        const result = await getAdvanceWechat({
            id: detail.value.recordId,
            detailOrderNo: detail.value?.detailOrderNo,
            transferScene: type || '',
        }).catch((err) => {
            data.title = '提现失败'
            data.status = 3
            data.type = 'error'
            data.content = err?.data?.msg || err?.msg || '网络错误，请稍后再试'
            data.color = '#FF7E68'
            toResult(data)
        })

        if (result && result.type === '转账失败') {
            data.title = '提现失败'
            data.status = 3
            data.type = 'error'
            data.content = result.msg
            toResult(data)
            return
        }
        else if (result && result.msg) {
            data.title = '提现中'
            data.type = 'success'
            data.status = 1
            data.content = result.msg
            data.color = '#04CD5A'
            toResult(data)
            return
        }
        data.title = '提现中'
        data.status = 1
        data.content = ''
        data.type = 'success'
        data.color = '#04CD5A'
        toResult(data)
    })
}

/**
 * 微信领薪到银行卡
 *
 * @returns 无返回值，执行过程中可能进行页面跳转
 */
async function onGetBank() {
    await isRegistryWechat()

    const idCardFront = !!user.userInfo.value?.ownIdCardFront

    if (detail.value.isNeedIdCardPhoto === 1 && detail.value.isShowPop === 1 && !idCardFront) {
        const event = await navigateTo({
            url: '/package-mine/pages/bank-id-card/bank-id-card',
        })
        event.eventChannel.emit('extraData', {
            extraData: {
                id: detail.value.recordId,
                isShowCollectOpenBankAddress: detail.value.isCollectOpenBankAddress,
                isCollectOpenBankCity: extraData.value?.isCollectOpenBankCity,
                isCollectOpenBankName: extraData.value?.isCollectOpenBankName,
            },
        })
        return
    }

    let toastContent = ''

    if (detail.value.isShowPop)
        toastContent = '应劳务公司要求，需要您填写完银行卡号码。'
    else if (extraData.value?.isCollectOpenBankName === 1 && !user.userInfo.value.openBankName)
        toastContent = '应劳务公司要求，需要您填写完银行开户行信息。'
    else if (extraData.value?.isCollectBankCardImg === 1 && !user.userInfo.value?.bankCardImg)
        toastContent = '应劳务公司要求，需要您提交银行卡照片。'

    if (toastContent) {
        toast(toastContent)
        toBank({
            id: detail.value.recordId,
            isShowCollectOpenBankAddress: detail.value.isCollectOpenBankAddress,
        })
        return
    }

    const isSalary = uni.getStorageSync('isSalary')

    if (!isSalary) {
        // #ifdef MP-ALIPAY
        my.reportCustomEvent('104527945', {
            bizType: 'cloudappevent',
            age: getCardAge(detail.value.idCardNo),
            salary_channel: '银行卡',
        })
        // #endif

        // 事件上报
        // #ifdef MP-WEIXIN
        // reportEvent('salary_card', {
        //     userid: user.userId,
        //     age: getCardAge(this.data.detailsList.idCardNo),
        //     salary_channel: '银行卡',
        // })
        // #endif
        uni.setStorageSync('isSalary', true)
    }

    try {
        const res = await querySalaryCard(detail.value.companyId).catch((err) => {
            if (err)
                toast('请去微信小程序开通微工卡')
            else
                toast('劳务公司暂未开通微工卡服务')

            throw new Error('没开通微工卡')
            // err ? toast('请去微信端开通微工卡') : toast('劳务公司暂未开通微工卡服务')
        })
        if (!res?.isOpenSalaryCard) {
            toast('劳务公司暂未开通微工卡服务')
            return
        }
        await hasNoContact()
        getPaid('BANK_ACCOUNT')
    }
    catch (err) {
        console.log(1111, err)
    }
}

async function navigateToNext(url: string) {
    const event = await navigateTo({
        url,
    })
    event.eventChannel.emit('extraData', {
        id: detail.value.recordId,
        isshowCollectOpenBankAddress: detail.value.isCollectOpenBankAddress,
        ...extraData.value,
    })
}

/**
 * 微信领薪到零钱
 *
 * @returns 无返回值，执行过程中可能进行页面跳转
 */
async function onGetWallet() {
    await isRegistryWechat()

    // 判断有没有合同
    await hasNoContact()
    const isSalary = uni.getStorageSync('isSalary')
    if (!isSalary) {
        // 上报埋点 等开通
        // reportEvent('salary', {
        //     'userid': user.userId,
        //     'age': getCardAge(this.data.detailsList.idCardNo),
        //     'salary_channel': '零钱'
        // })
        uni.setStorageSync('isSalary', true)
    }

    let hint = ''
    let url = '/package-mine/pages/bank-card/bank-card'
    console.log(extraData.value)

    if (detail.value.isShowPop)
        hint = '应劳务公司要求，需要您填写完银行卡号码。'

    if (extraData.value?.isCollectOpenBankName === 1 && !user.userInfo.value.openBankName)
        hint = '应劳务公司要求，需要您填写完银行开户行信息。'

    if (extraData.value?.isCollectOpenBankCity === 1 && !user.userInfo.value.openBankCity)
        hint = '应劳务公司要求，需要您填写完开户行城市信息。'

    if (detail.value.isNeedIdCardPhoto === 1 && !user.userInfo.value?.ownIdCardFront && !user.userInfo.value?.ownIdCardBack) {
        hint = '未上传身份证照片，请在上传后在进行领取。'
        url = '/package-mine/pages/card-info/card-info'
    }

    if (hint) {
        const res = await uni.showModal({
            title: '提示',
            content: hint,
        })
        if (res.confirm) {
            await navigateToNext(url)
            return
        }
        if (res.cancel)
            return
    }
    getPaid('WECHATPAY_ACCOUNT')
}

onMounted(() => {
    statusBarHeight.value = uni.getWindowInfo().statusBarHeight
    // #ifdef MP-ALIPAY
    my.setNavigationBar({
        frontColor: '#ffffff',
        backgroundColor: '#ffffff',
    })
    // #endif

    const instance = getCurrentInstance()?.proxy

    eventChannel.value = (instance as any)?.getOpenerEventChannel()

    eventChannel.value.on('extraData', (data: AnyObject) => {
        extraData.value = data || {}
        if (data.id) {
            id.value = data?.id
            getData(data.id)
        }
    })
})
</script>

<template>
    <NavbarContainer
        background-url="https://bullet001.oss-cn-shanghai.aliyuncs.com/file/payManager363631e9-06ab-476d-890f-a9978e34dd83.png">
        <view class="flex flex-col pt-80rpx">
            <view class="flex-1 px-30rpx pt-10rpx">
                <view
                    class="relative flex items-center rounded-lt-lg rounded-rt-lg bg-#f3f3f3 p-32rpx after:absolute before:absolute after:h-24rpx after:w-24rpx before:h-24rpx before:w-24rpx after:rounded-full before:rounded-full after:bg-primary before:bg-primary after:content-empty before:content-empty after:-bottom-12rpx after:-left-12rpx before:-bottom-12rpx before:-right-12rpx">
                    <view class="mr-32rpx text-lg">{{ detail.userName }}</view>
                    <view class="flex items-center">
                        <img class="mr-10px h-32rpx w-32rpx" src="../../assets/image/advance/icon-idcard.png" alt="">
                        <view class="text-base text-lightgray">{{ detail.idCardNo }}</view>
                    </view>
                </view>
                <view class="box-border rounded-lb-lg rounded-rb-lg bg-white px-32rpx py-28rpx">
                    <view class="mb-32rpx flex flex-col items-center border-1 border-b-#f8f8f8 border-b-solid pb-64rpx">
                        <view class="text-xs text-lightgray">预支金额（元）</view>
                        <view class="relative mt-40rpx">
                            <view class="text-76rpx text-black font-bold">{{ detail.advanceAmount }}</view>
                            <view
                                class="absolute border-1 border-green rounded-full rounded-bl-0 border-solid px-10rpx py-6rpx text-x2s text-green -right-80rpx -top-24rpx"
                                :class="{ 'text-yellow border-yellow': detail.endstatus === 0 || detail.endstatus === 6, 'text-red border-red': detail.endstatus === 1 || detail.endstatus === 4 || detail.endstatus === 5, 'text-green border-green': detail.endstatus === 2, 'text-blue border-blue': detail.endstatus === 3 }">
                                {{ statusMap[detail.endstatus] }}
                            </view>
                        </view>
                    </view>
                    <view class="text-xs">
                        <view class="flex justify-between py-16rpx">
                            <view class="text-lightgray">申请时间：</view>
                            <view>{{ dayjs(detail.advanceApplyTime).format('YYYY-MM-DD hh:mm:ss') }}</view>
                        </view>
                        <view class="flex justify-between py-16rpx">
                            <view class="text-lightgray">申请时用工企业：</view>
                            <view>{{ detail.serveCompanyName }}</view>
                        </view>
                        <view class="flex justify-between py-16rpx">
                            <view class="text-lightgray">员工备注：</view>
                            <view>{{ detail.applyRemark }}</view>
                        </view>
                        <view class="flex justify-between py-16rpx">
                            <view class="text-lightgray">预支单号：</view>
                            <view>{{ detail.advanceCode }}</view>
                        </view>
                        <view v-if="detail.endstatus === 1" class="flex justify-between py-16rpx">
                            <view class="text-lightgray">驳回原因：</view>
                            <view>{{ detail.payTime }}</view>
                        </view>
                        <view v-if="detail.endstatus === 2" class="flex justify-between py-16rpx">
                            <view class="text-lightgray">发放时间：</view>
                            <view>{{ detail.payTime }}</view>
                        </view>
                        <view v-if="detail.endstatus === 3" class="flex justify-between py-16rpx">
                            <view class="text-lightgray">领取时间：</view>
                            <view>{{ detail.getSalaryTime }}</view>
                        </view>
                        <view v-if="detail.endstatus === 4" class="flex justify-between py-16rpx">
                            <view class="text-lightgray">停止发薪时间：</view>
                            <view>{{ detail.stopTime }}</view>
                        </view>
                        <view v-if="detail.isShowContacts"
                              class="bg mx-auto mb-32rpx mt-64rpx h-96rpx w-562rpx flex items-center justify-center rounded-lg text-white"
                              @click="onCall">
                            <img class="mr-16rpx h-32rpx w-32rpx" src="../../assets/image/advance/icon-phone.png"
                                 alt="">
                            <view class="text-xs">联系驻厂</view>
                        </view>
                    </view>
                </view>
            </view>
        </view>
        <template v-if="showBottom" #button>
            <view v-if="showBottom && detail.status !== 1"
                  class="pos-fixed bottom-0 left-0 box-border w-full bg-#ffffff px-30rpx pt-10rpx pb-safe-20rpx">
                <view v-if="detail.status === SalaryStatusEnum['待领薪'] || detail.status === SalaryStatusEnum['领取失败']"
                      class="w-full pb-20rpx">
                    <view v-if="detail.payAccountFlag === 20001"
                          class="box-border h-88rpx w-full flex items-center justify-center rounded-44rpx bg-orange text-32rpx text-#ffffff"
                          @click="onGetSalary">
                        领取到支付宝账户
                    </view>
                    <view v-else>
                        <view class="flex gap-16rpx">
                            <view
                                class="h-88rpx flex flex-1 flex-col items-center justify-center border border-#DEE0E3 rounded-full border-solid text-center"
                                @click="onGetBank">
                                <view class="text-32rpx font-bold">微工卡提现</view>
                                <view class="text-20rpx text-textgray font-bold">自定义提现账户</view>
                            </view>
                            <view
                                class="set-button-bg relative h-88rpx flex flex-auto flex-col items-center justify-center rounded-full text-center text-white"
                                @click="onGetWallet">
                                <view class="text-32rpx font-bold">提现至微信零钱</view>
                                <view class="text-20rpx font-bold">极速领薪 秒到账</view>
                                <view
                                    class="absolute right-30rpx rounded-full rounded-lb-0 bg-#FDB114 px-16rpx py-4rpx text-24rpx text-white -top-20rpx">
                                    推荐
                                </view>
                            </view>
                        </view>
                    </view>
                </view>
            </view>
        </template>
        <pop-up v-model:show="showNoRegisterPopup" title="领取薪资">
            <view class="mt-30rpx text-center text-gray">
                打开微信，顶部搜索 <text class="text-black font-bold">“子弹工作”</text>
            </view>
            <view class="text-center text-gray">注册领薪</view>
            <image class="mx-auto mt-30rpx block h-327rpx w-530rpx" src="../../assets/image/salary/wx-image-1.png" />
        </pop-up>
    </NavbarContainer>
</template>

<style scoped>
.set-bg {
    background: url('https://bullet001.oss-cn-shanghai.aliyuncs.com/file/payManager363631e9-06ab-476d-890f-a9978e34dd83.png') no-repeat;
    height: 600rpx;
}

.bg {
    background: linear-gradient(180deg, #6196FF 0%, #4C7BFF 100%);
}

.set-button-bg {
    background: linear-gradient(-264deg, #FF8F34 3%, #FF363D 98%);
}
</style>

<route lang="json">
{
    "style": {
        "navigationBarTitleText": "预支详情",
        "mp-alipay": {
            "transparentTitle": "always"
        }
    }
}
</route>
